package com.example.zhu95.mytimber.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.PermissionChecker;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.zhu95.mytimber.MyApplication;
import com.example.zhu95.mytimber.R;
import com.example.zhu95.mytimber.entity.SongBean;
import com.example.zhu95.mytimber.entity.SongData;
import com.example.zhu95.mytimber.fragments.AlbumDetailFragment;
import com.example.zhu95.mytimber.fragments.ArtistDetailFragment;
import com.example.zhu95.mytimber.fragments.FoldersFragment;
import com.example.zhu95.mytimber.fragments.LibraryFragment;
import com.example.zhu95.mytimber.fragments.PlaylistFragment;
import com.example.zhu95.mytimber.fragments.PlayqueueFragment;
import com.example.zhu95.mytimber.fragments.SongsFragment;
import com.example.zhu95.mytimber.listener.AlbumClickListener;
import com.example.zhu95.mytimber.listener.ArtistClickListener;
import com.example.zhu95.mytimber.listener.OnMusicGestureListener;
import com.example.zhu95.mytimber.listener.PlayPauseBtnOnClickListener;
import com.example.zhu95.mytimber.listener.PlayPauseBtnOnTouchListener;
import com.tbruyelle.rxpermissions.RxPermissions;

import butterknife.BindView;
import butterknife.ButterKnife;
import jp.co.recruit_lifestyle.android.widget.PlayPauseButton;
import rx.functions.Action1;

import static com.example.zhu95.mytimber.ConstantValue.ALBUM_ID;
import static com.example.zhu95.mytimber.ConstantValue.ARTIST_ID;

/**
 * @author zhu95
 */
public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @BindView(R.id.btn_play_pause)
    PlayPauseButton btnPlayPause;
    @BindView(R.id.image_bottom_artist)
    ImageView imageBottomArtist;
    @BindView(R.id.v_progress)
    ProgressBar vProgress;
    @BindView(R.id.tv_bottom_song)
    TextView tvBottomSong;
    @BindView(R.id.tv_bottom_artist)
    TextView tvBottomArtist;
    @BindView(R.id.bottom_playing)
    View buttomPlaying;
    ImageView imgHeaderAlbum;

    LibraryFragment libraryFragment = null;
    PlaylistFragment playlistFragment = null;
    FoldersFragment foldersFragment = null;
    PlayqueueFragment playqueueFragment = null;
    AlbumDetailFragment albumDetailFragment = null;
    ArtistDetailFragment artistDetailFragment = null;

    private AlbumClickListener albumClickListener = new AlbumClickListener() {
        @Override
        public void clickAlbum(int albumid) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (albumDetailFragment == null) {
                albumDetailFragment = new AlbumDetailFragment();
            }
            Bundle bundle = new Bundle();
            bundle.putInt(ALBUM_ID, albumid);
            albumDetailFragment.setArguments(bundle);
            transaction.replace(R.id.fragment_container, albumDetailFragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    };
    private ArtistClickListener artistClickListener = new ArtistClickListener() {
        @Override
        public void clickArtist(int artistid) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (artistDetailFragment == null) {
                artistDetailFragment = new ArtistDetailFragment();
            }
            Bundle bundle = new Bundle();
            bundle.putInt(ARTIST_ID, artistid);
            artistDetailFragment.setArguments(bundle);
            transaction.replace(R.id.fragment_container, artistDetailFragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    };

    public AlbumClickListener getAlbumClickListener() {
        return albumClickListener;
    }

    public ArtistClickListener getArtistClickListener() {
        return artistClickListener;
    }

    @SuppressLint("ClickableViewAccessibility")
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (PermissionChecker.checkSelfPermission(MyApplication.getContext(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PermissionChecker.PERMISSION_GRANTED) {
            SongData.initData();
        } else {
            RxPermissions.getInstance(this)
                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(new Action1<Boolean>() {
                        @Override
                        public void call(Boolean aBoolean) {
                            if (!aBoolean) {
                                Toast.makeText(MyApplication.getContext(),
                                        R.string.no_permission, Toast.LENGTH_SHORT).show();
                                finish();
                            } else {
                                SongData.initData();
                            }
                        }
                    });
        }
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        // MARK: 2017/11/29在colors文件夹下创建相应的文件指定
        Resources resources = getResources();
        navigationView.setItemTextColor(resources.getColorStateList(R.color.navigation_menu_item_color, null));
        navigationView.setItemIconTintList(resources.getColorStateList(R.color.navigation_menu_item_color, null));

        View headerView = navigationView.inflateHeaderView(R.layout.nav_header_main);
        imgHeaderAlbum = headerView.findViewById(R.id.iv_header_album);

        //设置第一项默认选中
        navigationView.getMenu().getItem(0).setChecked(true);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        libraryFragment = new LibraryFragment();
        transaction.replace(R.id.fragment_container, libraryFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        // MARK:2017/11/25 setColor方法传入的int值是颜色值int而不是资源值int(R.color.colorAccent)
        //int color = Color.parseColor("#FF4081");
        btnPlayPause.setColor(getColor(R.color.colorAccent));

        Glide.with(MainActivity.this).load(R.drawable.ic_empty_music2).centerCrop().into(imageBottomArtist);
        Glide.with(MainActivity.this).load(R.drawable.ic_empty_music2).centerCrop().into(imgHeaderAlbum);
        //默认创建时先从数据库加载歌曲播放的数据
        //updateBottomUI(songid,MusicState_Stop,currentPosition);

        OnMusicGestureListener onMusicGestureListener = new OnMusicGestureListener() {
            //设置点击事件
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                Intent intent = new Intent(MainActivity.this, NowPlayingActivity.class);
                startActivity(intent);
                return super.onSingleTapConfirmed(e);
            }
        };
        onMusicGestureListener.enableDoubleClick(true);
        onMusicGestureListener.enableFling(true);
        final GestureDetector gestureDetector = new GestureDetector(MainActivity.this, onMusicGestureListener);

        buttomPlaying.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                gestureDetector.onTouchEvent(event);
                return true;
            }
        });

        PlayPauseBtnOnClickListener onControlStatusChangeListener = new PlayPauseBtnOnClickListener();
        btnPlayPause.setOnTouchListener(new PlayPauseBtnOnTouchListener(onControlStatusChangeListener));

        Intent intent = getIntent();
        int albumId = intent.getIntExtra(getString(R.string.go_album), -1);
        int artistId = intent.getIntExtra(getString(R.string.go_artist), -1);
        if (albumId > 0) {
            albumClickListener.clickAlbum(albumId);
        } else if (artistId > 0) {
            artistClickListener.clickArtist(artistId);
        }

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        int id = item.getItemId();

        if (id == R.id.nav_lib) {
            if (libraryFragment == null) {
                libraryFragment = new LibraryFragment();
            }
            transaction.replace(R.id.fragment_container, libraryFragment);
        } else if (id == R.id.nav_playlist) {
            if (playlistFragment == null) {
                playlistFragment = new PlaylistFragment();
            }
            transaction.replace(R.id.fragment_container, playlistFragment);
        } else if (id == R.id.nav_folders) {
            if (foldersFragment == null) {
                foldersFragment = new FoldersFragment();
            }
            transaction.replace(R.id.fragment_container, foldersFragment);
        } else if (id == R.id.nav_playqueue) {
            if (playqueueFragment == null) {
                playqueueFragment = new PlayqueueFragment();
            }
            transaction.replace(R.id.fragment_container, playqueueFragment);
        } else if (id == R.id.nav_now_playing) {
            Intent intent = new Intent(this, NowPlayingActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_setting) {

        } else if (id == R.id.nav_about) {

        }
        //transaction.addToBackStack(null);
        transaction.commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void updateUI(int songid, String musicState, int currentPosition) {
        super.updateUI(songid, musicState, currentPosition);

        updateBottomUI(songid, musicState, currentPosition);
        updateSongItem();
    }

    @Override
    public void updateProgress(int songid, final int currentPosition) {
        super.updateProgress(songid, currentPosition);
        final SongBean song = SongData.findSongByID(songid);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                vProgress.setMax(song.getDuration());
                vProgress.setProgress(currentPosition);
            }
        });
    }

    private void updateBottomUI(int songid, String state, int currentPosition) {
        //更改UI
        updatePlayPauseBtnState(btnPlayPause, state);

        SongBean song = SongData.findSongByID(songid);
        if (song == null) {
            return;
        }
        if (currentPosition != -1) {
            vProgress.setMax(song.getDuration());
            vProgress.setProgress(currentPosition);
        }
        String albumArt = song.getAlbumArt();
        if (!TextUtils.isEmpty(albumArt)) {
            Glide.with(MainActivity.this).load(albumArt).centerCrop().into(imageBottomArtist);
            Glide.with(MainActivity.this).load(albumArt).centerCrop().into(imgHeaderAlbum);
        } else {
            Glide.with(MainActivity.this).load(R.drawable.ic_empty_music2).centerCrop().into(imageBottomArtist);
            Glide.with(MainActivity.this).load(R.drawable.ic_empty_music2).centerCrop().into(imgHeaderAlbum);
        }
        String title = song.getTitle();
        String artist = song.getArtist();
        tvBottomSong.setText(title);
        tvBottomArtist.setText(artist);

        int duration = song.getDuration();
        vProgress.setMax(duration);
    }

    private void updateSongItem() {
        if (libraryFragment != null) {
            try {
                SongsFragment songsFragment = (SongsFragment) libraryFragment.getPagerAdapter().getSections()[0].getFragment();
                songsFragment.getAdapter().notifyDataSetChanged();
            } catch (Exception e) {
//                e.printStackTrace();
                Log.w(this.getClass().getName(), "updateSongItem: " + e.getMessage());
            }
        }
        if (playqueueFragment != null) {
            playqueueFragment.getItemVdragAdapter().notifyDataSetChanged();
        }
    }
}
